<template>
  <div class="image-container">
    <img
      :src="imageSrc"
      :style="imageStyle"
      @mouseover="startAnimation"
      @mouseout="resetAnimation"
      @click="toggleAnimation"
      alt="Animated image">
  </div>
</template>

<script>
export default {
  name: 'ZoomingImage',
  props: {
    imageSrc: {
      type: String,
      required: true
    },
    duration: {
      type: Number,
      default: 1 // 默认动画持续时间1秒
    },
    scale: {
      type: Number,
      default: 1.5 // 默认放大倍数
    },
    autoPlay: {
      type: Boolean,
      default: false // 是否自动播放动画
    }
  },
  data() {
    return {
      isZoomed: false,
      isAnimating: false
    }
  },
  computed: {
    imageStyle() {
      return {
        transform: this.isZoomed ? `scale(${this.scale})` : 'scale(1)',
        transition: this.isAnimating ? `transform ${this.duration}s ease-in-out` : 'none',
        cursor: 'pointer',
        display: 'block',
        maxWidth: '100%'
      }
    }
  },
  mounted() {
    if (this.autoPlay) {
      this.startAutoAnimation();
    }
  },
  methods: {
    startAnimation() {
      if (!this.autoPlay) {
        this.isAnimating = true;
        this.isZoomed = true;
      }
    },
    resetAnimation() {
      if (!this.autoPlay) {
        this.isAnimating = true;
        this.isZoomed = false;
      }
    },
    toggleAnimation() {
      this.isAnimating = true;
      this.isZoomed = !this.isZoomed;
    },
    startAutoAnimation() {
      setInterval(() => {
        this.isAnimating = true;
        this.isZoomed = !this.isZoomed;

        // 动画结束后重置动画状态
        setTimeout(() => {
          this.isAnimating = false;
        }, this.duration * 1000);
      }, this.duration * 2000); // 每2倍动画时间切换一次
    }
  }
}
</script>

<style scoped>
.image-container {
  display: inline-block;
  overflow: hidden;
}

img {
  will-change: transform; /* 优化动画性能 */
}
</style>
